package com.itheima.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    //1.定义一个变量，获取配置文件的地址
    @Value("${ruiJi.path}")
    private String basePath;

    //上传文件
    @PostMapping("/upload")
    public R upload(@RequestBody MultipartFile file) throws IOException {
        //2.获取文件后缀名
        String filename = file.getOriginalFilename();
        //3.截取字符串，获取后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //4.拼接id
        String uuid = UUID.randomUUID().toString();
        String id = uuid + suffix;
        //5.判断文件夹是否存在
        File dir = new File(basePath);

        //6.不存在就创建文件夹
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //7.将临时文件转移到指定文件
        try {
            file.transferTo(new File(basePath + id));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(id);
    }

    //下载文件
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //1.读取文件（输入流）
        FileInputStream fis = new FileInputStream(new File(basePath, name));
        //2.写数据（输出流）
        ServletOutputStream os = response.getOutputStream();
        //3.将读取的数据写到本地
        IoUtil.copy(fis, os);
        //4.关流
        fis.close();
        os.close();
    }
}
